package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"net/http"
)

func readBody(response *http.Response) []byte {
	reader := bufio.NewReader(response.Body)
	var res []byte
	for {
		temp := make([]byte, 100)
		_, err := reader.Read(temp)
		if err == io.EOF {
			break
		}
		res = append(res, temp...)
	}
	return res
}

func redirectLimitTime() {
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if len(via) > 10 {
				return errors.New("重定向次数过多")
			}
			return nil
		},
	}

	request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/redirect/20", nil)
	if err != nil {
		fmt.Printf("构建请求失败，err-->%v", err)
		return
	}
	response, err := client.Do(request)
	if err != nil {
		fmt.Printf("发起请求失败，err-->%v", err) //err-->Get "/relative-redirect/9": 重定向次数过多
		return
	}
	fmt.Println(string(readBody(response)))

}

func redirectForbidden() {
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	request, err := http.NewRequest(http.MethodGet, "http://httpbin.org/cookies/set?name=hedaodao", nil)
	if err != nil {
		fmt.Printf("构建请求失败，err-->%v", err)
		return
	}
	response, err := client.Do(request)
	if err != nil {
		fmt.Printf("发起请求失败，err-->%v", err)
		return
	}
	fmt.Println(response.Request.URL) //http://httpbin.org/cookies/set?name=hedaodao
}

func main() {
	//redirectLimitTime()
	redirectForbidden()
}
